<template>
  <view class="container">
    <view class="form">
      <view class="form-item">
        <text class="label">姓名</text>
        <input type="text" v-model="userContract.name" placeholder="请输入" @blur="validate('name')" />
      </view>

      <view class="form-item">
        <text class="label">联系电话</text>
        <input type="tel" v-model="userContract.phone" placeholder="请输入" @blur="validate('phone')" />
        <text v-if="phoneError" class="error">{{ phoneError }}</text>
      </view>

      <view class="form-item">
        <text class="label">备用联系方式</text>
        <input type="tel" v-model="userContract.backupContact" placeholder="请输入" @blur="validate('backupPhone')" />
        <text v-if="backupPhoneError" class="error">{{ backupPhoneError }}</text>
      </view>

      <view class="form-item">
        <text class="label">酒店地址</text>
        <input type="text" v-model="userContract.hotelAddress" placeholder="××省××市××区亚泉酒店" @blur="validate('hotelAddress')"/>
      </view>

      <view class="form-item">
        <text class="label">旅游线路</text>
        <view class="checkbox-group">
          <uv-checkbox-group @change="onRouteChange">
            <view class="checkbox-row">
              <label v-for="route in routes" :key="route" class="checkbox-label">
				<uv-checkbox :value="route" :checked="selectRoutes.includes(route.routeName)" :name="route.id"/>
                {{route.routeName}}
              </label>
            </view>
          </uv-checkbox-group>
        </view>
      </view>

      <view class="form-item">
        <text class="label">参与人数</text>
        <view class="number-input" v-for="(item, index) in userContract.participant" :key="index">
        <!-- <view class="number-input" v-for="(item, index) in userContract.participant" :key="index"> -->
          <text>{{item.label}}</text>
          <text class="item-price">¥{{item.price}}</text>
          <view class="counter">
            <button @click="decreaseCount(index)">-</button>
            <input type="number" v-model="item.count" />
            <button @click="increaseCount(index)">+</button>
          </view>
        </view>
      </view>

      <view class="form-item">
        <text class="label">需要支付金额</text>
        <view class="price_box modify-link-parent">
          <input type="number" :value="userContract.total" class="total-price" disabled />
          <text class="modify-link" @click="showModifyPriceModal">点击修改</text>
        </view>
      </view>
    </view>
    <button class="submit-btn" @click="submitForm">确认提交</button>
  </view>
</template>

<script>
import {routesList,editContract,getContract} from '../../../api/contract.js'
import { confirmTouristInfoAPI } from '../../../api/user.js'
  export default {
    data() {
      return {
		oid:'',
		userContract:{
			backupContact:'',
			hotelAddress:'',
			name:'',		
			participant: [{
				label: '成人',
				price:0,
				count:0
			  },
			  {
			    label: '老人学生',
				price:0,
				count:0
			  },
			  {
			    label: '儿童(一米三以下)',
				price:0,
				count:0
			  }
			],
			phone:'',
			selectedRoutes:[],
			total: 0,
			userId:0
		},
        routes:[{
			id:0,
			routeName:'',
			adultFee:0,
			oldStuFee:0,
			childrenFee:0
		},
		{
			id:0,
			routeName:'',
			adultFee:0,
			oldStuFee:0,
			childrenFee:0
		}],
		selectRoutes:[],
        error: {
        	name: '',
        	phone: '',
        	backupContact: '',
        	hotelAddress: ''        
        }
      }
    },
	onLoad(option) {
		this.oid=option.oid
		getContract(this.oid).then(res=>{
			this.userContract=res.data
		}),
		routesList().then(res=>{
			const {data} = res
			const legth = data.length || 0 
			for (var i = 0; i < legth; i++) {
				this.routes[i] = {}		
				this.routes[i].id=data[i].id
				this.routes[i].routeName=data[i].spotName
				this.routes[i].adultFee=data[i].adultFee
				this.routes[i].oldStuFee=data[i].oldStuFee
				this.routes[i].childrenFee=data[i].childrenFee
			}
		let result = [];
		for (let i = 0; i < this.userContract.selectedRoutes.length; i++) {
			for(let j=0;j<this.routes.length;j++){
				if (this.routes[j].id===this.userContract.selectedRoutes[i]) {
				  result.push(this.routes[j].routeName);
				  break;
				}
			}
		}
		this.selectRoutes=result
		})	
	
	},
    methods: {
		updateParticipantPrices() {
			let adultFee = 0;
			let oldStuFee = 0;
			let childrenFee = 0;
			
			for (var i = 0; i < this.userContract.selectedRoutes.length; i++) {
				for (var j = 0; j < this.routes.length; j++) {
					if(this.routes[j].id===this.userContract.selectedRoutes[i]){
						adultFee += this.routes[j].adultFee;
						oldStuFee += this.routes[j].oldStuFee;
						childrenFee += this.routes[j].childrenFee;
					}
				}
			}
		
			this.userContract.participant.forEach(participant => {
				switch (participant.label) {
					case '成人':
						participant.price = adultFee;
						break;
					case '老人学生':
						participant.price = oldStuFee;
						break;
					case '儿童(一米三以下)':
						participant.price = childrenFee;
						break;
				}
			});
			this.calculateTotal();
		},
      onRouteChange(e) {
		//任一个checkbox状态发生变化时触发，回调为一个对象
		this.userContract.selectedRoutes=e
		this.updateParticipantPrices();
      },
      decreaseCount(index) {
        if (this.userContract.participant[index].count > 0) {
          this.userContract.participant[index].count--;
        }
        this.calculateTotal();
      },
      increaseCount(index) {
        this.userContract.participant[index].count++;
        this.calculateTotal();
      },
      calculateTotal() {
			this.userContract.total = this.userContract.participant.reduce((total, item) => {
          return total + (item.price * item.count);
        }, 0);
      },
      validate(type) {
		   const phoneRegex = /^1[0-9]{10}$/;
		   if (type === 'phone' && !phoneRegex.test(this.userContract.phone)) {
			this.error.phone = '号码格式不正确';
		   } else if (type === 'phone') {
			this.error.phone = '';
		   }
		   if (type === 'backupContact' && !phoneRegex.test(this.userContract.backupContact)) {
			this.error.backupContact = '备用电话号码必须是以1开头的11位数字';
		   } else if (type === 'backupContact') {
			this.error.backupContact = '';
		   }
		   if (type === 'name' && !this.userContract.name) {
			this.error.name = '姓名不能为空'
		   } else if (type === 'name') {
			this.error.name = '';
		   }
		   if (type === 'hotelAddress' && !this.userContract.hotelAddress) {
			this.error.hotelAddress = '酒店地址不能为空'
		   } else if (type === 'hotelAddress') {
			this.error.hotelAddress = '';
		   }
      },
      showModifyPriceModal() {
        uni.showModal({
          title: '请输入金额',
          editable: true,
          success: (res) => {
            if (res.confirm) {
              this.userContract.total = res.content;
            }
          }
        });
      },
	  validateForm() {
	  	this.validate('name')
	  	this.validate('phone')
	  	this.validate('backupContact')
	  	this.validate('hotelAddress')
	  	if (this.error.name || this.error.backupContact || this.error.phone || this.error.hotelAddress) {
	  		uni.showToast({
	  			icon: 'none',
	  			title: '填写错误'
	  		})
	  		return false
	  	} else if (this.userContract.participant[0].count === 0&&this.userContract.participant[1].count===0&&this.userContract.participant[2].count===0) {
	  		uni.showToast({
	  			icon: 'none',
	  			title: '至少选择一人报名'
	  		})
	  		return false
	  	} else if (this.userContract.selectedRoutes.length === 0) {
	  		uni.showToast({
	  			icon: 'none',
	  			title: '至少选择一条旅游线路'
	  		})
	  		return false
	  	}
	  	return true
	  },
      async submitForm() {
		  if(this.validateForm()){
			   editContract(this.oid,this.userContract).then(res=>{
				uni.showToast({
					icon: 'success',
					title: '提交成功',
				})
				uni.navigateTo({
					url:'/pages/user/PendingPayment/PendingPayment?orderId='+this.oid
					// url:'/common/pages/order/order'
				})
			  })
			//更改订单状态
		    await confirmTouristInfoAPI(this.oid,'待支付')
		  }
      }
    }
  }
</script>

<style scoped>
  .container {
    padding: 20rpx;
  }

  .header {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .form-item {
    margin-bottom: 20rpx;
  }

  .label {
    display: block;
    margin-bottom: 10rpx;
    font-weight: 600;
  }

  input {
    width: 95%;
    height: 80rpx;
    background-color: #f5f7fa;
    border-radius: 10rpx;
    padding: 0 20rpx;
    border: 1rpx solid #ddd;
  }

  .checkbox-group {
    display: flex;
    flex-wrap: wrap;
    margin: auto;
    justify-content: center;
    align-items: center;
    width: fit-content;
    /* 这将使盒子的宽度只包含其内容，从而使盒子可以被居中 */
  }

  .checkbox-row {
    display: flex;
    flex-wrap: wrap;
    /* justify-content: center; */
    /* 水平居中 */
    align-items: center;
    /* 垂直居中，如果想在垂直方向上居中，需要确保flex-direction为column或者你的元素高度固定 */
  }

  .checkbox-label {
    display: flex;
    align-items: center;
    width: 30%;
    /* Adjusted to fit three in a row */
    margin-bottom: 10rpx;
    justify-content: flex-start;
    /* Ensure proper alignment */
  }

  .checkbox-label checkbox {
    margin-right: 10rpx;
  }

  .number-input {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10rpx;
  }

  .counter {
    display: flex;
    align-items: center;
  }

  .counter button {
    width: 60rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    background-color: #f5f7fa;
    border: 1rpx solid #ddd;
  }

  .counter input {
    width: 80rpx;
    text-align: center;
    border: 1rpx solid #ddd;
    height: 60rpx;
  }

  .item-price {
    color: red;
    font-size: 28rpx;
  }

  .price_box {
    display: flex;
    align-items: center;
    width: 97%;
    background-color: #f5f7fa;
    border-radius: 10rpx;
    padding: 10rpx;
    border: 1rpx solid #ddd;
  }

  .total-price {
    width: 100px;
    border: none;
    background: none;
    text-align: left;
    /* 确保金额数字左对齐 */
  }

  .modify-link-parent {
    display: flex;
    justify-content: space-between;
    /* 使“修改金额”文本靠右对齐，同时确保输入框靠左对齐 */
  }

  .modify-link {
    color: blue;
    text-decoration: none;
  }

  .submit-btn {
    width: 80%;
    height: 90rpx;
    line-height: 90rpx;
    background-color: #007AFF;
    color: white;
    text-align: center;
    border-radius: 20rpx;
    margin-top: 30rpx;
  }

  .error {
    color: red;
    font-size: 24rpx;
  }
</style>